import pymysql


class TDSQLCon:
    def __init__(self, host='localhost', port=3306, user='root', password='123456', db='testdb', charset='utf8'):
        self.host = host
        self.port = int(port)
        self.user = user
        self.password = password
        self.db = db
        self.charset = charset
        self.connection = None

    def get_connection(self):
        if not self.connection or not self.connection.open:
            self.connection = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                db=self.db,
                port=self.port,
                charset=self.charset
            )
        return self.connection

    def close_connection(self):
        if self.connection and self.connection.open:
            self.connection.close()
            self.connection = None



    def execute_update(self, sql, params=None):
        conn = self.get_connection()
        try:
            with conn.cursor() as cursor:
                affected_rows = cursor.execute(sql, params)
            conn.commit()
            return affected_rows
        except Exception as e:
            print("Error executing update:", e)
            conn.rollback()
        finally:
            self.close_connection()


